package com.weixin.pay.utils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom2.JDOMException;

import com.weixin.pay.entity.WeixinParameter;

public class PayCommonUtil {

	/**
	 * 生成随机字符串
	 * 
	 * @param length
	 * @return
	 */
	public static String createNoncestr(int length) {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < length; i++) {
			Random rd = new Random();
			res += chars.indexOf(rd.nextInt(chars.length() - 1));
		}
		return res;
	}

	public static String createNoncestr() {
		/*
		 * String chars =
		 * "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		 * String res = ""; for (int i = 0; i < 16; i++) { Random rd = new
		 * Random(); res += chars.charAt(rd.nextInt(chars.length() - 1)); }
		 * return res;
		 */
		return createNoncestr(16);
	}

	/**
	 * @author
	 * @date 2014-12-5下午2:29:34
	 * @Description：sign签名
	 * @param characterEncoding
	 *            编码格式
	 * @param parameters
	 *            请求参数
	 * @return
	 */
	public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		Set<?> es = parameters.entrySet();
		Iterator<?> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + ConfigUtil.API_KEY);
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}

	public static String createSign2(String characterEncoding, SortedMap<Object, Object> parameters, String api_key) {
		StringBuffer sb = new StringBuffer();
		Set<?> es = parameters.entrySet();
		Iterator<?> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + api_key);
		String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}

	/**
	 * @author
	 * @date 2014-12-5下午2:32:05
	 * @Description：将请求参数转换为xml格式的string
	 * @param parameters
	 *            请求参数
	 * @return
	 */
	public static String getRequestXml(SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set<?> es = parameters.entrySet();
		Iterator<?> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	/**
	 * @author
	 * @date 2014-12-3上午10:17:43
	 * @Description：返回给微信的参数
	 * @param return_code
	 *            返回编码
	 * @param return_msg
	 *            返回信息
	 * @return
	 */
	public static String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}

	public static String perPay(WeixinParameter info) throws JDOMException, IOException {
		SortedMap<Object, Object> param = new TreeMap<Object, Object>();
		param.put("appid", ConfigUtil.APPID);
		param.put("mch_id", ConfigUtil.MCH_ID);
		param.put("nonce_str", PayCommonUtil.createNoncestr());
		param.put("body", info.getComment());
		param.put("out_trade_no", info.getTradeNo());
		param.put("total_fee", info.getFee());
		param.put("spbill_create_ip", info.getIp());
		param.put("notify_url", ConfigUtil.NOTIFY_URL);// 支付成功后回调的action，与JSAPI相同
		param.put("trade_type", info.getTradeType());// "NATIVE"
		// parameters.put("product_id", "No.20140105003");//商品号要唯一
		String sign = PayCommonUtil.createSign("UTF-8", param);
		param.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(param);
		String result = CommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		System.out.println("------------------>"+result);
		Map<String, String> map = XMLUtil.doXMLParse(result);
		String returnCode = map.get("return_code");
		String resultCode = map.get("result_code");
		if (returnCode.equalsIgnoreCase("SUCCESS") && resultCode.equalsIgnoreCase("SUCCESS")) {
			
			
			// String codeUrl = map.get("code_url");
		}
		return "";

	}
}
